package core

class SysUserController {

	def index(){
		redirect(action: 'list')
	}

	def authenticate(String userName, String password) {
		def user =  SysUser.findByUserNameAndPassword("${userName}", "${password}")
		if(user){
			session.user = user
			flash.welcome = "Welcome ${user.userName}"
			redirect (action:'list')
		}
		else {
			flash.loginStatus="login failed: incorrect user name or password"
			redirect(action:'login')
		}

		//[user: SysUser.get(303)]
	}
	def login(){
		render(view:'login')
	}
	def logOut(){
		flash.logout = "goodbye ${session.user.userName}"

		session.user = null
		redirect(action:'login')
	}

	def save() {
		def user = new SysUser(params)
		if(user.save()){
			flash.userCreated = "User ${user?.userName}: was created"
			redirect(view:"list")
		}
		else {
			flash.userError = "User ${user?.userName}: failed to be created"
			render(view: 'create')
		}
	}
	def update(long id) {
		def user =  SysUser.get(id)
		user.properties = params
		if (user.save())
			redirect(action: "index")
	}
	def delete(long id){
		def user = SysUser.get(id)
		user.delete()
		redirect(action: 'index')
	}
	def list () {
		[users: SysUser.list()]
	}
	def edit(long id){
		[user: SysUser.get(id)]
	}
}
